package com.yuanlp.mobileplayer.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.yuanlp.mobileplayer.IMusicPlayerService;
import com.yuanlp.mobileplayer.R;
import com.yuanlp.mobileplayer.activity.AudioPlayerAcivity;
import com.yuanlp.mobileplayer.bean.MediaItem;
import com.yuanlp.mobileplayer.utils.CacheUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

public class MusicPlayerService extends Service {
    private static final String TAG = "MusicPlayerService";
    public static final String OPENAUDIOPLAYER = "com.yuanlp.mobilePlayer_openAudioPlayer";

    private int position;
    private ArrayList<MediaItem> medialist;
    private MediaItem item;
    private MediaPlayer mediaPlayer;
    private NotificationManager manger;  //状态栏通知管理器

    public static final int REPEAT_NORMAL=1;  //默认播放模式，即顺序播放
    public static final int REPEAT_SINGLE=2;  //单曲循环
    public static final int REPEAT_ALL=3;  //循环播放




    private int playMode=REPEAT_NORMAL;  //播放模式


    public MusicPlayerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        playMode=CacheUtils.getPlayMode(this,"playmode");
    }


    private IMusicPlayerService.Stub stub=new IMusicPlayerService.Stub() {

        MusicPlayerService service=MusicPlayerService.this;
        @Override
        public void openAudio(int position) throws RemoteException {
            System.out.println("调取了内部的方法传递position为"+position);
            service.openAudio(position);
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void startAudio() throws RemoteException {
            service.startAudio();
        }

        @Override
        public void pauseAudio() throws RemoteException {
            service.pauseAudio();
        }

        @Override
        public void stopAudio() throws RemoteException {
            service.stopAudio();
        }

        @Override
        public int getCurrentPosition() throws RemoteException {
            return service.getCurrentPosition();
        }

        @Override
        public long getDuration() throws RemoteException {
            return service.getDuration();
        }

        @Override
        public String getSinger() throws RemoteException {
            return service.getSinger();
        }

        @Override
        public long getSize() throws RemoteException {
            return service.getSize();
        }

        @Override
        public String getSong() throws RemoteException {
            return service.getSong();
        }

        @Override
        public String getAudioPath() throws RemoteException {
            return service.getAudioPath();
        }

        @Override
        public void getNext() throws RemoteException {
            service.getNext();
        }

        @Override
        public void getPre() throws RemoteException {
            service.getPre();
        }

        @Override
        public void setPlayMode(int playMode) throws RemoteException {
            service.setPlayMode(playMode);
        }

        @Override
        public int getPlayMode() throws RemoteException {
            return service.getPlayMode();
        }

        /**
         * 是否播放
         */
        @Override
        public boolean isPlaying() throws RemoteException {
            return service.isPlaying();
        }

        public void seekTo(int progress){
            service.seekTo(progress);

        }
    };

//  public class Mybinder extends Binder{
//      public MusicPlayerService getService(){
//          return MusicPlayerService.this;
//      }
//  }
//
//  public Mybinder binder=new Mybinder();
//    @Override
//    public IBinder onBind(Intent intent) {
//
//        return binder;
//
//    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("绑定了服务------------");

       medialist= (ArrayList<MediaItem>) intent.getSerializableExtra("medialist");
       System.out.println("获取服务里的数据。。。"+medialist.size());
        return stub;

    }

    /**
     * 根据对应位置打开音乐
     * @param position
     */
    private void openAudio(int position){
        this.position=position;
        Log.d(TAG, "openAudio:当前位置 "+position);
       item=medialist.get(position);
        Log.d(TAG, "openAudio: 当前位置对应的歌名"+item.getName());

        if (mediaPlayer!=null){
           //mediaPlayer.release();
           mediaPlayer.reset();
            mediaPlayer=null;
        }

        try {
            mediaPlayer=new MediaPlayer();
             mediaPlayer.setOnPreparedListener(new MyOnPreparedListener());
            mediaPlayer.setOnCompletionListener(new MyOnCompletionListener());
            mediaPlayer.setOnErrorListener(new MyOnErrorListener());
            mediaPlayer.setDataSource(item.getData());
            mediaPlayer.prepareAsync();

            if (playMode==REPEAT_SINGLE){
                mediaPlayer.setLooping(true);  //如果是单曲循环播放模式，那么就设置looping为true，不会触发播放完成会掉粉方法
            }else{
                mediaPlayer.setLooping(false);//其他播放模式looping设置为false
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 播放出错时回调
     */
    class MyOnErrorListener implements MediaPlayer.OnErrorListener {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            getNext();
            return true;
        }
    }
    /**
     * 播放完成时
     */
    class MyOnCompletionListener implements MediaPlayer.OnCompletionListener {


        @Override
        public void onCompletion(MediaPlayer mp) {
            getNext();
        }
    }
    /**
     * 准备好播放时回调
     */
    class MyOnPreparedListener implements MediaPlayer.OnPreparedListener {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onPrepared(MediaPlayer mp) {
           startAudio();
            //在这里发送广播，通知activity，播放的进度、音乐名称、歌唱家等信息
//            notifyChange(OPENAUDIOPLAYER);

            //EventBus发布信息
            EventBus.getDefault().post(item);
        }
    }

    /**
     * 发送广播通知activity
     * @param openaudioplayer
     */
    private void notifyChange(String openaudioplayer) {
        Intent intent=new Intent(openaudioplayer);
        sendBroadcast(intent);
    }

    /**
     * 播放音乐
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void startAudio(){
        mediaPlayer.start();
        manger= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  //获取系统的通知服务
        //Notification notifaction= null;

            Intent intent=new Intent(this, AudioPlayerAcivity.class);  //点击通知栏后，打开activity音乐界面
            Bundle bundle=new Bundle();
            bundle.putSerializable("mediallist",medialist);
            intent.putExtras(bundle);
            intent.putExtra("Notifaction",true);  //标识来自状态栏
            //intent.putExtra("position",position);  //将当前的位置带过去
            //System.out.println("service里的-----当前进度"+mediaPlayer.getCurrentPosition());
            //intent.putExtra("currentPosition",mediaPlayer.getCurrentPosition());  //当前进度带过去
            PendingIntent pendingintent=PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notifaction = new Notification.Builder(this)
                    .setSmallIcon(R.drawable.notification_music_playing)
                    .setContentTitle("原立鹏音乐播放器")
                    .setContentText("正在播放:"+getSong())
                    .setContentIntent(pendingintent)
                    .build();

        manger.notify(1,notifaction);

    }

    /**
     * 暂停音乐
     */
    public void pauseAudio(){
        mediaPlayer.pause();

        //停止播放时取消状态栏
        manger.cancel(1);
    }

    /**
     * 停止音乐
     */
    public void stopAudio(){
        mediaPlayer.stop();
    }

    /**
     * 得到当前播放进度
     * @return
     */
    public int getCurrentPosition(){

        return mediaPlayer.getCurrentPosition();
    }

    /**
     * 得到总时长
     * @return
     */
    public long getDuration(){

        return mediaPlayer.getDuration();
    }

    /**
     * 得到演唱者
     * @return
     */
    public String getSinger(){

        return item.getArtist();
    }

    /**
     * 得到音乐大小
     * @return
     */
    public long getSize(){

        return item.getSize();
    }

    /**
     * 得到歌名
     * @return
     */
    public String getSong(){

        return item.getName();
    }

    /**
     * 得到路径
     * @return
     */
    public String getAudioPath(){

        return item.getData();
    }

    /**
     * 得到下一首
     */
    public void getNext(){
        //根据当前的播放模式，设置下一个的位置
        setNextPosition();
        //2 根据播放模式及下标，播放音乐
        openNextAudiao();
    }

    private void openNextAudiao() {
        //playMode=getPlayMode();
        if (playMode==MusicPlayerService.REPEAT_NORMAL){
            System.out.println("默认模式，position="+position);
            if (position<medialist.size()){
                openAudio(position);
            }else{
                    position=medialist.size()-1;
            }

        }else if (playMode==MusicPlayerService.REPEAT_SINGLE){
            System.out.println("单曲模式，position="+position);
            openAudio(position);
        }else if (playMode==MusicPlayerService.REPEAT_ALL){
            System.out.println("循环模式，position="+position);
            openAudio(position);
        }else {
            if (position<medialist.size()){
                openAudio(position);
            }else{
                position=medialist.size()-1;
            }
        }
    }

    private void setNextPosition() {
        playMode=getPlayMode();
        if (playMode==MusicPlayerService.REPEAT_NORMAL){
            System.out.println("当前模式，默认顺序");
            position+=1;

        }else if (playMode==MusicPlayerService.REPEAT_SINGLE){
            System.out.println("当前模式，单曲");
            position++;
            if (position>=medialist.size()){
                position=0;
            }


        }else if (playMode==MusicPlayerService.REPEAT_ALL){
            System.out.println("当前模式，循环");
            position++;
            if (position>=medialist.size()){
                position=0;
            }

        }else {
            position++;

        }
    }

    /**
     * 得到上一首
     */
    public void getPre(){
        //获取播放模式
        getPrePosition();
        //根据播放模式与位置，来播放
        openPreAudio();


    }

    private void openPreAudio() {
        if (playMode==REPEAT_NORMAL){
            if (position>0){
                openAudio(position);
            }else{
                position=0;
            }

        }else if (playMode==REPEAT_SINGLE){
            openAudio(position);

        }else if (playMode==REPEAT_ALL){
            openAudio(position);
        }
    }

    private void getPrePosition() {
        playMode=getPlayMode();
        if (playMode==REPEAT_NORMAL){
            position-=1;

        }else if (playMode==REPEAT_SINGLE){
            position-=1;
            if (position<0){
                position=medialist.size()-1;
            }

        }else if (playMode==REPEAT_ALL){
            position-=1;
            if (position<0){
                position=medialist.size()-1;
            }
        }
    }

    /**
     * 设置播放模式
     * @param playMode
     */
    public void setPlayMode(int playMode){
        this.playMode=playMode;
        CacheUtils.putPlayMode(this,"playmode",playMode);
        if (playMode==REPEAT_SINGLE){
            mediaPlayer.setLooping(true);  //如果是单曲循环播放模式，那么就设置looping为true，不会触发播放完成会掉粉方法
        }else{
            mediaPlayer.setLooping(false);//其他播放模式looping设置为false
        }
    }

    /**
     * 得到播放模式
     */
    public int getPlayMode(){
        return playMode;
    }

    public boolean isPlaying(){
        return mediaPlayer.isPlaying();
    }

    public void seekTo(int progress){
        mediaPlayer.seekTo(progress);
    }
}
